import axios from 'axios'
import { setLocalForage } from '../utils/localForage'

export function flatList () {
  return axios({
    method: 'get',
    url: `${process.env.VUE_APP_BOOK_URL}/book/flat-list`
  })
}

export function home () {
  // return axios({
  //   method: 'get',
  //   url: `${process.env.VUE_APP_BASE_URL}/book/home`
  // })
  // 也可
  // return
  return axios.get(`${process.env.VUE_APP_BASE_URL}/book/home`)
}

export function detail (book) {
  return axios.get(`${process.env.VUE_APP_BOOK_URL}/book/detail`, {
    params: {
      fileName: book.fileName
    }
  })
}

export function list () {
  return axios.get(`${process.env.VUE_APP_BASE_URL}/book/list`)
}

export function shelf () {
  return axios({
    method: 'get',
    url: `${process.env.VUE_APP_BASE_URL}/book/shelf`
  })
}

export function download (book, onSuccess, onError, onProgress) {
  // 当用户只传输三个参数时候，将第四个参数传输给第三个参数
  if (!onProgress) {
    onProgress = onError
    onError = null
  }
  return axios.create({
    baseURL: process.env.VUE_APP_EPUB_URL,
    method: 'get',
    responseType: 'blob',
    timeout: 180 * 1000,
    onDownloadProgress: progressEvent => {
      // 当有onProgress时候，将参数传输过去
      if (onProgress) onProgress(progressEvent)
    }
  }).get(`${book.categoryText}/${book.fileName}.epub`).then(res => {
    const blob = new Blob([res.data]) // 将下载完的结果中的数据生成一个Blob对象，epub.js可以直接打开
    setLocalForage(book.fileName, blob, () => {
      if (onSuccess) onSuccess(book)
    }, err => {
      if (onError) onError(err)
    })
  }).catch(err => {
    if (onError) onError(err)
  })
}
